<script setup lang="tsx">
import { ref, reactive } from 'vue';
import { ElButton } from 'element-plus';
import DynamicTable from '@/components/DynamicTable/index.vue';

const tableData = ref<any[]>([
  {
    id: 1,
    name: '张三',
    status: '启用',
    imageUrl: 'https://via.placeholder.com/100x100',
  },
  {
    id: 2,
    name: '李四',
    status: '禁用',
    imageUrl: 'https://via.placeholder.com/100x100',
  },
]);

const tableColumnConfig = ref([
  { prop: 'index', label: 'Index', width: '150', type: 'index' },
  { prop: 'selection', label: '多选', width: '150', type: 'selection' },
  { prop: 'selection', label: '单选', width: '150', type: '' },
  { prop: 'name', label: '姓名', width: '150' },
  { prop: 'status', label: '状态', width: '100' },
  {
    prop: 'imageUrl',
    label: '图片',
    width: '120',
    render: (scope: any) =>
      scope.row.imageUrl ? (
        <img
          src={scope.row.imageUrl}
          onClick={() => handleImageClick(scope.row)}
        />
      ) : (
        <span> --- </span>
      ),
  },
  {
    label: '操作',
    type: 'action',
    actions: [
      {
        label: '编辑',
        type: 'primary',
        action: 'edit',
        render: (scope: any) => (
          <ElButton
            type="primary"
            onClick={() => console.log('编辑:', scope.row)}
          >
            编辑
          </ElButton>
        ),
      },
      {
        label: '删除',
        type: 'danger',
        action: 'delete',
        render: (scope: any) => (
          <span
            style="color: red; cursor: pointer;"
            onClick={() => console.log('删除:', scope.row)}
          >
            删除
          </span>
        ),
      },
    ],
  },
]);

const tableConfig = reactive({
  total: 2,
  page: 1,
  pageSize: 10,
});

// 图片点击事件处理
const handleImageClick = (row: any) => {
  console.log('图片点击，行数据:', row);
};

// 监听子组件发出的按钮点击事件
const handleActionClick = (action: string, row: any) => {
  if (action === 'edit') {
    console.log('编辑操作，行数据:', row);
  } else if (action === 'delete') {
    console.log('删除操作，行数据:', row);
  }
};

// 分页事件处理
const updatePage = (newPage: number) => {
  tableConfig.page = newPage;
  // 重新获取数据...
};

const updatePageSize = (newSize: number) => {
  tableConfig.pageSize = newSize;
  tableConfig.page = 1; // 每页条数变化时重置为第一页
  // 重新获取数据...
};

const handleRowSelectionChange = (selectedRows: any[]) => {
  console.log('选中的行:', selectedRows);
};
</script>

<template>
  <div>
    <DynamicTable
      :tableData="tableData"
      :tableColumnConfig="tableColumnConfig"
      :total="tableConfig.total"
      :current-page.sync="tableConfig.page"
      :page-size.sync="tableConfig.pageSize"
      :height="500"
      :border="true"
      @updatePage="updatePage"
      @updatePageSize="updatePageSize"
      @rowSelectionChange="handleRowSelectionChange"
      @actionClick="handleActionClick"
    />
  </div>
</template>
